package org.maurange.formation.licpro;

import java.util.ArrayList;

import org.maurange.formation.licpro.rest.Arret;
import org.maurange.formation.licpro.rest.ArretRestMethod;
import org.maurange.formation.licpro.rest.ListArret;


import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.sip.SipAudioCall.Listener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;



public class ListArretsActivity extends ListActivity implements LocationListener
{
	private static String LOG_TAG="ListArretsActivity";
	private static ListLoadAsyncTask asyncTask = null;
	private static ArretAdapter arretAdapter;
	private LocationManager lm = null;
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        asyncTask = (ListLoadAsyncTask) getLastNonConfigurationInstance();
        
        this.lm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        
        this.arretAdapter = new ArretAdapter(this, new ArrayList<Arret>());
        setListAdapter(arretAdapter);
        
        this.getListView().setOnItemClickListener(new onClickItemListListener());
       
    }
    
    public class onClickItemListListener implements OnItemClickListener
    {
    	public onClickItemListListener()
    	{
    		
    	}
    	
		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
		{
			// TODO Auto-generated method stub
			Bundle objetbunble = new Bundle();
			objetbunble.putString("code",arretAdapter.getListArret().get(arg2).getCodeLieu());
			Intent intent = new Intent(ListArretsActivity.this, ArretDetailsActivity.class);
			intent.putExtras(objetbunble);
			startActivityForResult(intent,0);
		}
    }
    
    public Object onRetainNomConfigurationInstance()
    {	
    	asyncTask.detach();
    	
		return asyncTask;
    }

	@Override
	protected void onResume() {
		super.onResume();
		Log.d(LOG_TAG, "enregistrement des listeners");
		
        this.lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);

		if (this.lm.isProviderEnabled(LocationManager.GPS_PROVIDER))
		{
			Location loc = this.lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
			//loc.setLatitude(47.1800145);
			//loc.setLongitude(-1.5363273);

			//TODO     
	        if (this.asyncTask == null)
	        {
	        	this.asyncTask = new ListLoadAsyncTask(arretAdapter);
	        	this.asyncTask.attach(this);
	        	asyncTask.execute(loc.getLatitude(), loc.getLongitude());
	        }
	        
	        else
	        {
	        	try
	    		{
	    			arretAdapter.getListArret().clear();
	    		}
	    		
	    		catch (Exception e)
	    		{
	    			Log.d(LOG_TAG, "La liste ne peut pas être clear, peut être parce que la liste est déjà vide.");
	    		}
	        	
	        	asyncTask.detach();
	        	asyncTask.cancel(true);
	        	this.asyncTask = new ListLoadAsyncTask(arretAdapter);
	        	this.asyncTask.attach(this);
	        	asyncTask.execute(loc.getLatitude(), loc.getLongitude());
	        }
			
		}
	}
	
	//arret des updates
	@Override
	protected void onPause() {
		super.onPause();
		Log.d(LOG_TAG, "desenregistrement des listeners");
		//TODO
		this.lm.removeUpdates(this);
	}
	
	static private class ListLoadAsyncTask extends AsyncTask<Double, Integer, ListArret>
	{
		private Activity activity;
		private ArretAdapter adapter;
		
		public ListLoadAsyncTask(ArretAdapter adapt)
		{
			super();
			this.adapter = adapt;
		}

		protected void onPostExecute(ListArret list)
		{
			this.adapter.getListArret().addAll(list);
			this.adapter.notifyDataSetChanged();
		}

		/*
		protected void onProgressUpdate(Double... tabArg)
		{
		}*/
		
		@Override
		protected ListArret doInBackground(Double... tabArg)
		{
			ArretRestMethod arm = new ArretRestMethod(activity);
			ListArret list = arm.getArretsRest(tabArg[0],tabArg[1]);
			return list;
		}
		
		public void detach()
		{
			this.activity = null;
		}
		
		public void attach(Activity act)
		{
			this.activity = act;
		}
		
	}

	@Override
	public void onLocationChanged(Location loc)
	{
		// TODO Auto-generated method stub
		
		if (asyncTask.getStatus().equals(AsyncTask.Status.RUNNING) || (asyncTask.getStatus().equals(AsyncTask.Status.PENDING)))
		{
			asyncTask.detach();
        	asyncTask.cancel(true);
		}
		
		try
		{
			arretAdapter.getListArret().clear();
		}
		
		catch (Exception e)
		{
			Log.d(LOG_TAG, "La liste ne peut pas être clear, peut être parce que la liste est déjà vide.");
		}
		
		this.asyncTask = new ListLoadAsyncTask(arretAdapter);
		this.asyncTask.attach(this);
		asyncTask.execute(loc.getLatitude(), loc.getLongitude());
		
	}

	@Override
	public void onProviderDisabled(String arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onProviderEnabled(String arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
		// TODO Auto-generated method stub
		
	}
    
}
